package com.lagou.edu.controller;

import com.lagou.service.EmailService;
import com.lagou.service.LagouAuthCodeService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @author caiwei
 * @date 2020-11-18 22:52
 */
@RestController
@RequestMapping("/api/code")
public class AuthCodeController {

    @Reference
    private LagouAuthCodeService lagouAuthCodeService;

    @Reference
    private EmailService emailService;

    @Value("${config.email.templates.checkcode.title}")
    private String emailTitle;

    @Value("${config.email.templates.checkcode.content}")
    private String emailContent;

    /**
     * 生成验证码并发送到邮箱，成功返回true,失败返回false
     *
     */
    @GetMapping("/create/{email}")
    public String createAuthCode(@PathVariable("email")String email){
        System.out.println("========获取验证码=======");
        //1、校验该邮箱在一分钟之内是否有发送过验证码
        boolean b = lagouAuthCodeService.validateOneSendCode(email);
        if(!b){
            return "该邮箱在一分钟之内有发送过验证码";
        }
        //2.生成验证码
        String code = getRandomCode();
        lagouAuthCodeService.createAuthCode(email, code);
        //3.发送到邮箱
        long l1 = System.currentTimeMillis();
        String message = String.format(emailContent, code);
        Boolean aBoolean = emailService.sendEmail(email, emailTitle, message);
        long l2 = System.currentTimeMillis();
        System.out.println("远程所需时长："+(l2-l1)+";返回数据结果："+aBoolean);
        if(aBoolean){
            return "请到邮箱查看验证码!";
        }else{
            return "发送验证码失败！";
        }

    }

    /**
     * 校验验证码是否正确
     * 0-正确，1-错误，2-超时
     * @param email
     * @param code
     * @return
     */
    @GetMapping("/validate/{email}/{code}")
    public int validateAuthCode(@PathVariable("email") String email, @PathVariable("code") String code) {
        return lagouAuthCodeService.validateAuthCode(email, code);
    }

    /**
     *
     *随机生成6位数
     */
    private String getRandomCode(){
        Random random = new Random();
        String result="";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        return result;
    }
}
